package lixp.jwt.utils.Imp;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lixp.jwt.utils.IJwtUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Data
@ConfigurationProperties( prefix = "config.jwt" )
@Component
public class JwtUtilForJwt implements IJwtUtils {


    private String secret;
    private long expire;
    private String header;

    @Override
    public String creatToken(Integer userId) {


        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + expire);// 2小过期

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        Algorithm algorithm = Algorithm.HMAC256(secret);
        String token = JWT.create()
                .withHeader(map)
                /* 设置 载荷 Payload */
                .withAudience(userId.toString())
                .withIssuedAt(nowDate) // 生成签名的时间
                .withExpiresAt(expireDate)// 签名过期的时间
                /* 签名 Signature */
                .sign(algorithm);

        return token;


    }


    @Override
    public Integer getUserIdFromToken(String token) {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = verifier.verify(token);
        String s = jwt.getAudience().get(0);

        return Integer.parseInt(s);

    }
}
